package cascade.controller.pages.commands
{
	import cascade.App;
	import cascade.model.Page;
	
	import flight.commands.AsyncCommand;
	import flight.net.RemoteService;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.Fault;

	public class CommandLoadPages extends AsyncCommand
	{
		
		public override function execute():*
		{
			Cascade.busy.addBusy(this);
			
			Cascade.service.SiteService.loadPages(result, fault);
		}
		
		protected function result(pages:Array):void {
			var flat:ArrayCollection = new ArrayCollection();
			var tree:ArrayCollection = new ArrayCollection();
			
			var last:Page;
			var parent:Page;
			
			for (var i:Number = 0; i < pages.length; i++) {
				var page:Page = pages[i];
				flat.addItem(page);
				
				if (last) {
					if (page.depth > last.depth) {
						parent = last;
					} else if (page.depth < last.depth) {
						var diff:int = last.depth - page.depth;
						while (diff--) parent = parent.parent;
					}
				}
				
				if (page.depth == 0) {
					tree.addItem(page);
				} else {
					if (!parent.children)
						parent.children = new ArrayCollection();
					parent.children.addItem(page);
				}
				
				page.parent = parent;
				last = page;
			}
			
			Cascade.model.pages = flat;
			Cascade.model.siteTree = tree;
			
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
		
		protected function fault(info:Object):void {
			trace(info.faultString);
			
			Cascade.busy.removeBusy(this);
		}
	}
}